package com.m3839.sdk.ym.ui

import android.app.Activity
import android.content.pm.ActivityInfo
import android.os.Bundle
import android.text.SpannableString
import android.text.Spanned
import android.text.TextUtils
import android.text.method.LinkMovementMethod
import android.view.Gravity
import android.view.KeyEvent
import android.view.View
import android.widget.EditText
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import com.m3839.sdk.ym.base.YMBaseDialogFragment
import com.m3839.sdk.ym.constant.YMCodeConstant
import com.m3839.sdk.ym.constant.YMParamConstant
import com.m3839.sdk.ym.constant.YMStringConstant
import com.m3839.sdk.ym.core.YMManager
import com.m3839.sdk.ym.core.YMStorage
import com.m3839.sdk.ym.core.YMUIStackManager
import com.m3839.sdk.ym.ext.dip2px
import com.m3839.sdk.ym.ext.getDrawableId
import com.m3839.sdk.ym.ext.getId
import com.m3839.sdk.ym.util.ConditionUtils
import com.m3839.sdk.ym.util.EditTextUtils
import com.m3839.sdk.ym.util.InputUtils
import com.m3839.sdk.ym.util.ToastUtils
import com.m3839.sdk.ym.widget.DigitKeyboard
import com.m3839.sdk.ym.widget.PSClickableSpan
import com.m3839.sdk.ym.widget.PasswordEditText

/**
 * @description: YMPasswordDialogFragment
 *
 * @author ChenBaoyang
 * @date 6/16/21 16:18
 */
open class YMPasswordDialogFragment : YMBaseDialogFragment(), DigitKeyboard.DigitKeyboardClickListener,
    PasswordEditText.PasswordFullListener {

    /**
     * 表示当前的页面的操作行为是哪个：设置密码，确认密码，修改密码，设置新密码，再次输入新密码，关闭青少年模式
     */
    protected lateinit var action: String

    /**
     * 界面标题
     */
    protected lateinit var title: String

    /**
     * 按钮文案
     */
    protected lateinit var buttonText: String

    /**
     * 描述内容
     */
    protected lateinit var content: String

    /**
     * 密码保存
     */
    protected lateinit var mPassword: String

    /**
     * 上一层界面传进来的密码
     */
    private lateinit var password: String

    private lateinit var closeBtn: ImageView
    private lateinit var titleTv: TextView
    private lateinit var contentTv: TextView
    private lateinit var sureBtn: TextView
    private lateinit var exitGameBtn: TextView
    private lateinit var getPwdTv: TextView
    private lateinit var confirmTv: TextView
    private lateinit var llKeyboard: LinearLayout
    private lateinit var dialogPasswordEdit: EditText

    private lateinit var pwdEdit: PasswordEditText
    private lateinit var keyboard: DigitKeyboard

    private var defaultOrientation = 0

    companion object{
        fun show(activity: Activity, action: String, title: String,
                 content: String, buttonText: String, password: String, tag:String) {
            val fragment = YMPasswordDialogFragment()
            val data = Bundle()
            data.putString(YMParamConstant.YM_KEY_ACTION, action)
            data.putString(YMParamConstant.YM_KEY_TITLE, title)
            data.putString(YMParamConstant.YM_KEY_CONTENT, content)
            data.putString(YMParamConstant.YM_KEY_BUTTON_TEXT, buttonText)
            data.putString(YMParamConstant.YM_KEY_PASSWORD, password)
            fragment.arguments = data
            fragment.show(activity.fragmentManager, tag)
        }
    }

    override fun parseArgs() {
        defaultOrientation = YMStorage.instance.getDefaultOrientation(activity, -1)
        action = arguments.getString(YMParamConstant.YM_KEY_ACTION).toString()
        title = arguments.getString(YMParamConstant.YM_KEY_TITLE).toString()
        content = arguments.getString(YMParamConstant.YM_KEY_CONTENT).toString()
        buttonText = arguments.getString(YMParamConstant.YM_KEY_BUTTON_TEXT).toString()
        password = arguments.getString(YMParamConstant.YM_KEY_PASSWORD).toString()
    }

    override fun layoutName() =
        if (defaultOrientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) "ym_page_password_land" else "ym_page_password"


    override fun initView(view: View?) {
        closeBtn = view!!.findViewById(getId("btn_close"))
        titleTv = view.findViewById(getId("tv_title"))
        contentTv = view.findViewById(getId("tv_content"))
        sureBtn = view.findViewById(getId("btn_sure"))
        exitGameBtn = view.findViewById(getId("tv_exit_game"))
        getPwdTv = view.findViewById(getId("tv_get_password"))
        pwdEdit = view.findViewById(getId("et_password"))
        keyboard = view.findViewById(getId("custom_key_board"))

        if (defaultOrientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            llKeyboard = view.findViewById(getId("ll_keyboard"))
            dialogPasswordEdit = view.findViewById(getId("et_dialog_password"))
            confirmTv = view.findViewById(getId("tv_confirm"))
            confirmTv.text = YMStringConstant.YM_FCM_CONFIRM_BUTTON_TEXT
        }
    }

    override fun setContent() {

        titleTv.text = title
        contentTv.text = content
        sureBtn.text = buttonText
        exitGameBtn.text = YMStringConstant.YM_FCM_EXIT_GAME

        if (YMParamConstant.YM_VALUE_ACTION_CONTINUE_FCM == action) {
            exitGameBtn.visibility = View.VISIBLE
            if (defaultOrientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
                //横屏
                val layoutParams = LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT
                )
                layoutParams.gravity = Gravity.RIGHT
                layoutParams.topMargin = activity.dip2px(14f)
                getPwdTv.layoutParams = layoutParams
                getPwdTv.gravity = Gravity.CENTER or Gravity.RIGHT
            }
        } else {
            exitGameBtn.visibility = View.GONE
        }
        setHighLightText()
    }

    private fun setHighLightText() {
        if (YMParamConstant.YM_VALUE_ACTION_SET_PASSWORD == action
            || YMParamConstant.YM_VALUE_ACTION_CONFIRM_PASSWORD == action
            || YMParamConstant.YM_VALUE_ACTION_SET_NEW_PASSWORD == action
            || YMParamConstant.YM_VALUE_ACTION_CONFIRM_NEW_PASSWORD == action
        ) {
            getPwdTv.visibility = View.GONE
            return
        }
        getPwdTv.visibility = View.VISIBLE
        val spannableInfo = SpannableString(
            YMStringConstant.YM_FCM_GET_PASSWORD_TIP
        )
        spannableInfo.setSpan(
            PSClickableSpan(
            View.OnClickListener { //判断开发者是否有设置联系方式
                val contact: String? = YMManager.instance.getContact()
                if (TextUtils.isEmpty(contact)) {
                    ToastUtils.showToast(
                        activity,
                        YMStringConstant.YM_TOAST_CONTACT_EMPTY
                    )
                } else {
                    YMContactDialogFragment.show(activity)
                }
            }), 4, 8, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        )
        getPwdTv.text = spannableInfo
        getPwdTv.movementMethod = LinkMovementMethod.getInstance()
    }

    override fun initListener() {
        keyboard.setOnDigitKeyboardClickListener(this)
        pwdEdit.setOnPasswordFullListener(this)

        if (YMParamConstant.YM_VALUE_ACTION_CONTINUE_FCM == action
            || YMParamConstant.YM_VALUE_ACTION_NIGHT_MODE == action
        ) {
            closeBtn.visibility = View.GONE
        } else {
            closeBtn.visibility = View.VISIBLE
        }

        closeBtn.setOnClickListener { dismiss() }

        sureBtn.setOnClickListener {
            if (!ConditionUtils.isFastDoubleClick) {
                handleButtonEvent()
            }
        }

        exitGameBtn.setOnClickListener {
            if (YMParamConstant.YM_VALUE_ACTION_CONTINUE_FCM.equals(action)) {
                YMManager.instance.handleCallBack(
                        YMCodeConstant.YM_CODE_EXIT_GAME,
                    YMCodeConstant.YM_MSG_EXIT_GAME
                    )
                YMUIStackManager.instance!!.finishAllFragment()
            }
        }

        pwdEdit.isEnabled = true
        pwdEdit.isFocusable = false
        pwdEdit.isFocusableInTouchMode = false
        pwdEdit.setOnClickListener {
            if (defaultOrientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
                llKeyboard.visibility = View.VISIBLE
            }
            keyboard.visibility = View.VISIBLE
        }
        InputUtils.disableCopyAndPaste(pwdEdit)
        if (defaultOrientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            dialogPasswordEdit.isEnabled = true
            dialogPasswordEdit.isFocusable = false
            dialogPasswordEdit.isFocusableInTouchMode = false
            InputUtils.disableCopyAndPaste(dialogPasswordEdit)
        }
        setConfirmDialogButtonClickListener()
    }

    /**
     * 处理按钮的点击事件（该方法可以进继承复写）
     */
    protected open fun handleButtonEvent() {
        val currentPassword = pwdEdit.text.toString()
        val oldPassword: String? = YMStorage.instance.getPassword(activity, "")
        val defaultPassword: String = YMStorage.instance
            .getDefaultPassword(activity, "3839")
        val pass = currentPassword == oldPassword || currentPassword == defaultPassword
        when (action) {
            YMParamConstant.YM_VALUE_ACTION_SET_PASSWORD -> show(
                activity,
                YMParamConstant.YM_VALUE_ACTION_CONFIRM_PASSWORD,
                YMStringConstant.YM_FCM_CONFIRM_PASSWORD,
                YMStringConstant.YM_FCM_SET_PASSWORD_TIP,
                YMStringConstant.YM_FCM_NEXT_STEP,
                currentPassword,
                YMStringConstant.YM_FRAGMENT_TAG_PWD_CONFIRM
            )
            YMParamConstant.YM_VALUE_ACTION_CONFIRM_PASSWORD -> if (currentPassword == password) {
                //保存密码
                YMStorage.instance.savePassword(activity, currentPassword)
                //开启防沉迷，设置新的防沉迷开启标志
                YMManager.instance.setNewFcm(true)
                //开启防沉迷，心跳功能
                YMManager.instance.startFcm(-1)
                if (YMManager.instance.isInNightMode()) {
                    // 开启防沉迷的时候，刚好处于夜间模式，不打开 防沉迷已开启的界面
                    //关闭掉前面的所有页面
                    YMUIStackManager.instance!!.finishAllFragment()
                    return
                }
                //进入到防沉迷已开启的界面
                YMModeDialogFragment.show(
                    activity,
                    isOpenFcm = true,
                    isNightMode = false,
                    isNewFcm = true,
                    isCloseAllPre = true,
                    tag = YMStringConstant.YM_FRAGMENT_TAG_MODE_OPEN_NEW
                )
            } else {
                ToastUtils.showToast(activity, YMStringConstant.YM_TOAST_PASSWORD_DIFF)
                pwdEdit.setText("")
                clearDialogPasswordEdit()
            }
            YMParamConstant.YM_VALUE_ACTION_MODIFY_PASSWORD -> if (pass) {
                //新旧密码相同，进入设置新密码界面
                show(
                    activity,
                    YMParamConstant.YM_VALUE_ACTION_SET_NEW_PASSWORD,
                    YMStringConstant.YM_FCM_SET_NEW_PASSWORD,
                    "",
                    YMStringConstant.YM_FCM_NEXT_STEP,
                    "",
                    YMStringConstant.YM_FRAGMENT_TAG_PWD_MODIFY
                )
            } else {
                ToastUtils.showToast(activity, YMStringConstant.YM_TOAST_PASSWORD_ERROR)
                pwdEdit.setText("")
                clearDialogPasswordEdit()
            }
            YMParamConstant.YM_VALUE_ACTION_SET_NEW_PASSWORD -> show(
                activity,
                YMParamConstant.YM_VALUE_ACTION_CONFIRM_NEW_PASSWORD,
                YMStringConstant.YM_FCM_CONFIRM_NEW_PASSWORD,
                "",
                YMStringConstant.YM_FCM_NEXT_STEP,
                currentPassword,
                YMStringConstant.YM_FRAGMENT_TAG_PWD_SET_NEW
            )
            YMParamConstant.YM_VALUE_ACTION_CONFIRM_NEW_PASSWORD -> if (currentPassword == password) {
                //保存密码
                YMStorage.instance.savePassword(activity, currentPassword)
                //关闭掉前面的所有页面
                YMUIStackManager.instance!!.removeAboveFragments(YMStringConstant.YM_FRAGMENT_TAG_MODE_OPEN_NEW)
                //如果刚好跟防沉迷倒计时结束冲突了, 修改完密码还是跳转到继续青少年模式界面
                YMManager.instance.checkFcmNotTime()
            } else {
                ToastUtils.showToast(
                    activity,
                    YMStringConstant.YM_TOAST_PASSWORD_DIFF
                )
                pwdEdit.setText("")
                clearDialogPasswordEdit()
            }
            YMParamConstant.YM_VALUE_ACTION_CLOSE_FCM -> if (pass) {
                //密码一致关闭防沉迷
                YMManager.instance.closeFcm()
                //关防沉迷相关的所有页面
                YMUIStackManager.instance!!.finishAllFragment()
            } else {
                ToastUtils.showToast(
                    activity,
                    YMStringConstant.YM_TOAST_PASSWORD_ERROR
                )
                pwdEdit.setText("")
                clearDialogPasswordEdit()
            }
            /*YMParamConstant.HYKB_VALUE_ACTION_NIGHT_MODE -> if (pass) {
                YMManager.instance.ignoreNightMode()
                //关闭页面返回游戏
                dismiss()
            } else {
                ToastUtils.showToast(
                    activity,
                    YMStringConstant.HYKB_TOAST_PASSWORD_ERROR
                )
                pwdEdit.setText("")
                clearDialogPasswordEdit()
            }*/
            YMParamConstant.YM_VALUE_ACTION_CONTINUE_FCM -> if (pass) {
                //开启防沉迷，设置新的防沉迷开启标志
                YMManager.instance.setNewFcm(true)
                //如果继续输入密码，曾再次进行一次防沉迷累计
                YMManager.instance.startFcm(-1)
                // 展示悬浮气泡
                YMManager.instance.setShowFcmPop()
                //保存当前已经累计时长
                YMManager.instance.saveFcmNotTime()
                //关闭页面返回游戏
                dismiss()
            } else {
                ToastUtils.showToast(
                    activity,
                    YMStringConstant.YM_TOAST_PASSWORD_ERROR
                )
                pwdEdit.setText("")
                clearDialogPasswordEdit()
            }
        }
    }

    override fun click(number: String?) {
        pwdEdit.addPassword(number!!)
        addDialogPasswordEdit()
    }

    override fun delete() {
        pwdEdit.deleteLastPassword()
        if (defaultOrientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            EditTextUtils.deleteLastPassword(dialogPasswordEdit)
        }
    }

    override fun hidKeyBoard() {
        if (defaultOrientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            llKeyboard.visibility = View.INVISIBLE
        }
    }

    override fun passwordFull(password: String?) {
        mPassword = password!!
        setButtonStatus(true)
        if (defaultOrientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            setConfirmButtonStatus(true)
        }
    }

    override fun passwordChanged(password: String?) {
        mPassword = password!!
        setButtonStatus(false)
        if (defaultOrientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            setConfirmButtonStatus(false)
        }
    }


    open fun clearDialogPasswordEdit() {
        if (defaultOrientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            dialogPasswordEdit.setText("")
        }
    }

    open fun addDialogPasswordEdit() {
        if (defaultOrientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            val currentPassword = pwdEdit.text.toString()
            dialogPasswordEdit.setText(currentPassword)
        }
    }

    protected open fun setButtonStatus(enable: Boolean) {
        sureBtn.isEnabled = enable
        sureBtn.setBackgroundResource(
            if (enable) getDrawableId(
                "hykb_bg_open_button"
            ) else getDrawableId( "hykb_bg_disable_button")
        )
    }

    protected open fun setConfirmButtonStatus(enable: Boolean) {
        confirmTv.isEnabled = enable
        confirmTv.setBackgroundResource(
            if (enable) getDrawableId("hykb_bg_keyboard_confirm_button_press"
            ) else getDrawableId("hykb_bg_keyboard_confirm_button_normal"
            )
        )
    }

    open fun setConfirmDialogButtonClickListener() {
        if (defaultOrientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE && confirmTv != null) {
            confirmTv.setOnClickListener {
                if (!ConditionUtils.isFastDoubleClick) {
                    ConditionUtils.resetLastTimeClick()
                    llKeyboard.visibility = View.INVISIBLE
                }
            }
        }
    }


    override fun isInterceptBackEvent(event: KeyEvent): Boolean {
        val isConsum = keyboard.dispatchKeyEventInFullScreen(event)
        val needForbidden = handleBackEventForFcm(event)
        return isConsum || needForbidden
    }

    /**
     * 针对弹出继续防沉迷和夜间模式的返回键做处理
     *
     * @param event 系统的按键事件对象
     */
    private fun handleBackEventForFcm(event: KeyEvent): Boolean {
        return (YMParamConstant.YM_VALUE_ACTION_CONTINUE_FCM == action
                || YMParamConstant.YM_VALUE_ACTION_NIGHT_MODE == action)
    }
}